<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>CONVERSATION</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="/js/jquery-1.7.2.min.js"></script>
<style type="text/css">
.send{
	text-align:center;
	 position: absolute;
	 top: 93%;
	 left:18%;
	 z-index:999;
	 width:auto;
	 height:auto;
	 border:1px none solid;
	}
.messagea{
	height: 435px;
	float: left;
	width: 50%;
/* 	background: green; */
}	
/* .messageb{ */
/* 	height: 435px; */
/* /*   	background: green;  */ */
/* 	float: left; */
/* 	width: 50%; */
/* }	 */
</style>
</head>
<body>
	<div >
		当前USER&nbsp;<a style="color: red;" th:text="${id} ">&nbsp;</a>&nbsp;和USER&nbsp;<a style="color: red;"  th:text=" ${who} "></a>&nbsp;正在会话：<br/>
		<div class="messagea" id="messagea"></div>
<!-- 		<div class="messageb" id="messageb"></div> -->
		<div class="send">
			<input id="text" type="text" />&nbsp;<button onclick="send()">Send</button>
<!-- 			<button onclick="closeWebSocket()">Close</button> -->
		</div>
		
		<input type="hidden" th:value="${id}" id="sid"></input>
		<input type="hidden" th:value="${who}" id="who"></input>
	<script type="text/javascript">
		var sid=null;
		sid=document.getElementById('sid').value;
		var who=null;
		who=document.getElementById('who').value;
	    var websocket = null;
	    //判断当前浏览器是否支持WebSocket
	    if('WebSocket' in window){
	        websocket = new WebSocket("ws://localhost:8080/websocket/"+sid);
	    }
	    else{
	        alert('Not support websocket')
	    }
	
	    //连接发生错误的回调方法
	    websocket.onerror = function(){
	        setMessageInnerHTMLa("error");
	    };
	
	    //连接成功建立的回调方法
	    websocket.onopen = function(event){
	        setMessageInnerHTMLa("open");
	    }
	
	    //接收到消息的回调方法
	    websocket.onmessage = function(event){
	        setMessageInnerHTMLb(event.data);
	    }
	
	    //连接关闭的回调方法
	    websocket.onclose = function(){
	        setMessageInnerHTMLa("close");
	    }
	
	    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	    window.onbeforeunload = function(){
	        websocket.close();
	    }
	
	    //将消息自己发送的消息显示在网页上
	    function setMessageInnerHTMLa(innerHTML){
	        document.getElementById('messagea').innerHTML +="USER"+sid+":"+'<br/>'+innerHTML + '<br/>';
	    }
	   //将消息对方发送的消息显示在网页上
	    function setMessageInnerHTMLb(innerHTML){
	        document.getElementById('messagea').innerHTML +="USER"+who+":"+'<br/>'+innerHTML + '<br/>';
	    }
	
	    //关闭连接
	    function closeWebSocket(){
	        websocket.close();
	    }
	
	    //发送消息
	    function send(){
	    	var say=document.getElementById('text').value;
	        var message =who+':'+say;
	        setMessageInnerHTMLa(say);
	        document.getElementById('text').value="";
	        websocket.send(message);
	    }
	</script>
	</div>
</body>
</html>